import FSMMonster from "./FSMMonster";
import { IndicatorColorType } from "./Indicator";
import { FSMState } from "./lib/FSMState";
import Move from "./Move";

const _v1 = cc.v2();

export default class MonsterPatrolState extends FSMState {
    private _speed: number = 150;

    private _move: Move = null;
    private _monster: FSMMonster = null;

    onEnter() {
        super.onEnter();
        this._move = this.fsm.node.getComponent(Move);
        this._move.speed = this._speed;
        this._monster = this.fsm.node.getComponent(FSMMonster);
        cc.director.getScheduler().enableForTarget(this);
        this.fsm.node.on(Move.EventType.STOP, this.onMoveStop, this);
        this.onMoveStop();
    }

    public update(dt: any): void {
        if (this._monster.player.getPosition().subSelf(this._monster.gold.getPosition()).len() >= this._monster.goldRange) {
            this._monster.indicator.setColorType(IndicatorColorType.SAFE);
        } else {
            this._monster.indicator.setColorType(IndicatorColorType.WARM);
            //玩家进入视野范围
            if (this._monster.player.getPosition().subSelf(this.fsm.node.getPosition()).len() < this._monster.monsterRange) {
                this._monster.indicator.setColorType(IndicatorColorType.DANGE);
                this.fsm.data.setData("isHeroInRange", true);
            }
        }
    }

    public onEixt(): void {
        this.fsm.node.off(Move.EventType.STOP, this.onMoveStop, this);
        cc.director.getScheduler().unscheduleAllForTarget(this);
        this._move.stop();
        super.onEixt();
    }

    private onMoveStop() {
        //待机一段时间，去下一个地点巡逻
        cc.director.getScheduler().schedule(this.onIdleEnd, this, 2 + Math.random() * 2, 0, 0, false);
    }

    private onIdleEnd() {
        this._move.moveToDestination(this.getDestination());
    }

    private getDestination() {
        return this._monster.gold.getPosition().addSelf(cc.Vec2.random(_v1, this._monster.goldRange * Math.random()));
    }
}
